package com.ruoyi.stock.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.stock.domain.StockInventory;
import com.ruoyi.stock.service.IStockInventoryService;
import com.ruoyi.stock.service.IStockCheckService;

/**
 * 库存检查服务实现类
 * 
 * @author ruoyi
 * @date 2025-06-21
 */
@Service("stockCheckService")
public class StockCheckServiceImpl implements IStockCheckService 
{
    @Autowired
    private IStockInventoryService stockInventoryService;

    /**
     * 检查库存是否足够
     * 
     * @param productId 商品ID
     * @param quantity 需要的数量
     * @return 结果消息，如果为null表示检查通过
     */
    @Override
    public String checkStock(Long productId, Integer quantity) 
    {
        // 参数检查
        if (productId == null) {
            return "商品ID不能为空";
        }
        
        if (quantity == null || quantity <= 0) {
            return "数量必须大于0";
        }
        
        // 查询库存记录
        StockInventory inventory = new StockInventory();
        inventory.setProductId(productId);
        List<StockInventory> list = stockInventoryService.selectStockInventoryList(inventory);
        
        if (list == null || list.isEmpty()) {
            return "该商品未建立库存记录，请先创建库存记录";
        }
        
        // 获取库存信息
        StockInventory stockInventory = list.get(0);
        
        // 检查库存状态
        if ("1".equals(stockInventory.getStatus())) {
            return "该商品库存已被锁定，暂时无法使用";
        }
        
        // 检查库存数量
        if (stockInventory.getCurrentQuantity() < quantity) {
            return String.format("库存不足，当前库存: %d，需要: %d", 
                stockInventory.getCurrentQuantity(), quantity);
        }
        
        // 返回null表示检查通过
        return null;
    }
} 